import { Message, Table, Tag } from '@arco-design/web-react';
import { checkPermission } from '@src/components/ability';
import { confirmDialog } from '@src/components/dialog';
import LoadingMask from '@src/components/loadingMask';
import { dictTag } from '@src/components/tableColumn';
import TextButton from '@src/components/textButton';
import { detailRemove } from '@src/redux/detailReducer';
import { createStorePaginateListKey, paginateRequest } from '@src/redux/paginateReducer';
import { AppStore } from '@src/types';
import useDict from '@src/utils/dict';
import { clearEmptyKey, findTagColor } from '@src/utils/utils';
import { useEffect, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import DictDataDetailPage from './dictDataDetailPage';
import { DictData } from './types';
interface Props {
  type: string;
}

const model = 'system';
const table = 'dict/data';

// 系统开关 状态
const SYS_NORMAL_DISABLE = 'sys_normal_disable';
export default function DictDataListPage({ type }: Props) {
  const dispatch = useDispatch();

  const dictDatas = useDict(SYS_NORMAL_DISABLE);

  const [detailId, setDetailId] = useState<number | string>();
  // 创建请求参数 及检索key 按页面要求修改
  function createParams() {
    return clearEmptyKey({ dictType: type, orderByColumn: 'createTime', isAsc: 'desc' });
  }

  // 当前页需要的数据
  const list = useSelector(
    (state: AppStore) =>
      state.paginate[createStorePaginateListKey({ model, table, pageNum: 1, pageSize: 1000, params: createParams() })],
    shallowEqual
  );
  // 页面初始化时请求数据
  useEffect(() => {
    handleRefreshData(createParams());
  }, []); //eslint-disable-line

  /**
   * 刷新数据
   * @param _pageNum 页码
   * @param _pageSize 每页数量
   * @param params 查询参数
   * @param forceRefresh 是否强制刷新 强制刷新会清除当前数据的所有列表，重新请求接口，否则优先读取缓存数据
   */
  function handleRefreshData(params?: any, forceRefresh?: boolean, callback?: (code?: number, msg?: string) => void) {
    dispatch(
      paginateRequest({
        model,
        table,
        params,
        pageNum: 1,
        pageSize: 1000,
        forceRefresh,
        callback,
      })
    );
  }

  // 修改 操作列内的修改
  function handleEdit(record?: DictData) {
    setDetailId(record?.dictCode ?? 'create');
  }

  // 列表项双击事件 一般是进详情
  function handleDoubleClick(record: DictData) {
    let hasPermission = checkPermission('system:dict:edit');
    if (hasPermission) {
      setDetailId(record.dictCode);
    }
  }

  // 删除 弹窗确认
  async function handleDelete(record?: DictData) {
    let datas = record ? [record] : [];
    if (!datas.length) {
      return Message.warning('请选择数据');
    }
    let tipsRes = await confirmDialog({ content: '确定要删除吗' });
    if (tipsRes !== 1) return;
    let ids = datas.map((i) => i.dictCode).join(',');
    LoadingMask.show('正在删除...');
    dispatch(
      detailRemove({
        model,
        table,
        id: ids,
        callback(code, msg) {
          let _msg = code === 200 ? Message.success : Message.warning;
          handleRefreshData(createParams(), true);
          LoadingMask.hide();
          _msg(msg ?? '');
        },
      })
    );
  }

  let dataSource: DictData[] = list?.results || [];
  dataSource = dataSource.map((item) => Object.assign({}, item, { key: item.dictCode }));

  // 定义类型表格内的列
  const columns = [
    {
      title: '字典编码',
      dataIndex: 'dictCode',
      key: 'dictCode',
    },
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
      key: 'dictLabel',
      render: (v: string, _r: DictData) => (
        <Tag bordered={false} color={findTagColor(_r.listClass)}>
          {v}
        </Tag>
      ),
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      key: 'dictValue',
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort',
      key: 'dictSort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) => dictTag(v, dictDatas[SYS_NORMAL_DISABLE]),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: (
        <div className="d-flex-r">
          <TextButton
            text="刷新"
            onClick={() =>
              handleRefreshData(createParams(), true, () => {
                Message.success('已刷新');
              })
            }
          />
          <TextButton text="新增" permission={['system:dict:add']} onClick={() => handleEdit()} />
        </div>
      ),
      render: (_: any, record: DictData) => (
        <div className="d-flex-r jc-start text-primary-color">
          <TextButton text="编辑" permission={['system:dict:edit']} onClick={() => handleEdit(record)} />
          <TextButton text="删除" red permission={['system:dict:remove']} onClick={() => handleDelete(record)} />
        </div>
      ),
    },
  ];

  return (
    <div>
      <Table
        data={dataSource}
        columns={columns}
        pagination={false}
        loading={!list || (list.fetching && !list.loaded)}
        onRow={(record: any) => ({
          onDoubleClick: () => handleDoubleClick(record),
        })}
      />
      {!!detailId && (
        <DictDataDetailPage
          id={detailId}
          dictType={type}
          onCancel={(v?: boolean) => {
            setDetailId(undefined);
            if (v) {
              handleRefreshData(createParams(), true);
            }
          }}
        />
      )}
    </div>
  );
}
